namespace core {

    export class NetWork {
        private _websocket: egret.WebSocket
        private _msgHandleMgr: IMessageHandleMgr
        private _isconnected: boolean = false

        public OnConnect: (net: NetWork) => void
        public OnReceive: (net: NetWork, cmd: egret.ByteArray) => void
        public OnClose: (net: NetWork) => void
        public get IsConnected(): boolean {
            return this._isconnected
        }
        public set MsgHandleMgr(mgr: IMessageHandleMgr) {
            this._msgHandleMgr = mgr
        }
        public get MsgHandleMgr(): IMessageHandleMgr {
            return this._msgHandleMgr
        }

        constructor() {
            this._websocket = new egret.WebSocket()

            this._websocket.addEventListener(egret.Event.CONNECT, this.onSocketOpen, this)
            this._websocket.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.onReceiveMessage, this)
            this._websocket.addEventListener(egret.Event.CLOSE, this.onSocketClose, this)
            this._websocket.type = egret.WebSocket.TYPE_BINARY
        }
        private onSocketOpen(): void {
            this._isconnected = true
            if (this.OnConnect) {
                this.OnConnect(this)
            }
        }
        private onReceiveMessage(e: egret.Event): void {
            var cmdBuf = new egret.ByteArray()
            this._websocket.readBytes(cmdBuf)
            if (this._msgHandleMgr != null) {
                this._msgHandleMgr.Process(cmdBuf)
            }
            if (this.OnReceive) {
                this.OnReceive(this, cmdBuf)
            }
        }
        private onSocketClose(e: egret.Event): void {
            this._isconnected = false
            if (this.OnClose) {
                this.OnClose(this)
            }
        }

        public Connect(host: string, port: number) {
            this._websocket.connect(host, port)
        }
        public Send<T>(index: number, cmd: T) {
            if (this._msgHandleMgr != null) {
                let buf = this._msgHandleMgr.Pack(index, cmd)
                if (buf) {
                    this._websocket.writeBytes(buf)
                }
            }
        }
    }
}